package com.training;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class ProductPageIT {
    private WebDriver driver;

    @BeforeClass
    public static void setupClass() {
        WebDriverManager.chromedriver().setup();
    }

    @Before
    public void setUp() {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless"); // 无头模式，不显示浏览器窗口
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-dev-shm-usage");
        driver = new ChromeDriver(options);
    }

    @After
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void testProductListPage() {
        // 访问产品列表页面
        driver.get("http://localhost:8080/products");

        // 验证页面标题
        String pageTitle = driver.findElement(By.tagName("h1")).getText();
        assertEquals("Product List", pageTitle);

        // 验证表格头部
        List<WebElement> headers = driver.findElements(By.tagName("th"));
        assertEquals(4, headers.size());
        assertEquals("ID", headers.get(0).getText());
        assertEquals("Product Name", headers.get(1).getText());
        assertEquals("Price", headers.get(2).getText());
        assertEquals("Stock", headers.get(3).getText());

        // 验证产品数据
        List<WebElement> rows = driver.findElements(By.cssSelector("table tr"));
        // 减去表头行
        assertEquals(4, rows.size()); // 3个产品 + 1个表头行

        // 验证第一个产品的数据
        WebElement firstRow = rows.get(1); // 第二行（第一个产品）
        List<WebElement> cells = firstRow.findElements(By.tagName("td"));
        assertEquals("1", cells.get(0).getText());
        assertEquals("Laptop", cells.get(1).getText());
        assertEquals("$999.99", cells.get(2).getText());
        assertEquals("10", cells.get(3).getText());

        // 验证页面样式
        WebElement table = driver.findElement(By.tagName("table"));
        String tableStyle = table.getAttribute("style");
        assertTrue("Table should have width style", 
            tableStyle != null && tableStyle.contains("width") && tableStyle.contains("80%"));
    }
} 